import { GlobalStore } from "@/store/GlobalStore";
import OSS from "ali-oss";
import { useEffect, useRef } from "react";
import { ApiHttp } from "@/network/ApiHttp";
import { StoreStatus } from "@/utils/makeStore";


export function useOSS() {
  const ossRef = useRef<OSS>();
  const [{ sts, session_id }, dispatch, status] = GlobalStore.useStore();
  useEffect(() => {
    if (status !== StoreStatus.Initialized) return;
    if (!session_id) return;
    const c = new AbortController();
    ApiHttp.post('user/oss_sts', void 0, void 0, { ...c })
      .then(r => dispatch({ type: 'sts_info', payload: r.data }))
      .catch(ApiHttp.ignoreAbort)
      .catch(ApiHttp.ignore401)
      .catch(e => console.error(e, e?.cause));
    return () => c.abort();
  }, [dispatch, session_id, status]);

  useEffect(() => {
    if (!sts.securityToken) return;
    ossRef.current = new OSS({
      region: "oss-cn-guangzhou",
      accessKeyId: sts.accessKeyId,
      accessKeySecret: sts.accessKeySecret,
      stsToken: sts.securityToken,
      bucket: "gim-ink",
      refreshSTSToken: async () => {
        const payload = await ApiHttp.post('user/oss_sts').then(r => r.data);
        GlobalStore.dispatch({ type: 'sts_info', payload });
        return {
          accessKeyId: payload.accessKeyId,
          accessKeySecret: payload.accessKeySecret,
          stsToken: payload.securityToken
        };
      },
      refreshSTSTokenInterval: 1000
    });
  }, [sts]);
  return ossRef;
}
